import React, {Fragment, PureComponent} from 'react';
import {connect} from 'dva';
import moment from 'moment';
import {Badge, Button, Card, Col, Form, Modal, Row, Select} from 'antd';
import TableList from '@/components/TableList';
import ApplyDetailForm from './sub/ApplyDetailForm';
import styles from './Out.less';

const FormItem = Form.Item;
const getValue = obj =>
  Object.keys(obj)
    .map(key => obj[key])
    .join(',');
const applyType = ['个人文件下载', '公共文件下载', '流转', '外发', '编辑','自定义组文件下载'];
const statusMap = ['processing', 'success', 'error'];
const status = ['申请中', '通过', '拒绝'];


@connect(({auditModel, loading}) => ({
  auditModel,
  loading: loading.models.auditModel,
}))
@Form.create()
class AuditDone extends PureComponent {
  state = {
    selectedRows: [],
    formValues: {},
    waterOptions:[],
    authOptions: [],
  };

  columns = [
    {
      title: '文件名称',
      dataIndex: 'fileNames',
      width: "30%",
      render: (text) => (
        <div className={styles.colRemark} title={text}>
          {text}
        </div>
      )
    },
    {
      title: '申请人',
      dataIndex: 'applyUserName',
    },

    {
      title: '申请来源',
      render(val) {
        return applyType[val.applyType];
      },
    },

    {
      title: '审批时间',
      dataIndex: 'updateTime',

      render: (val) => {
        if (val) {
          return <span>{moment(val).format('YYYY-MM-DD HH:mm:ss')}</span>
        } else {
          return null;
        }
      }
    },
    {
      title: '状态',
      dataIndex: 'applyState',
      render(val) {
        return <Badge status={statusMap[val]} text={status[val]}/>;
      },
    },
    {
      title: '操作',
      render: (text, record) => (
        <Fragment>
          <a onClick={() => this.handleModalVisible(true, record)}>查看</a>
        </Fragment>
      ),
    },
  ];

  componentDidMount() {
    this.queryAuditPageList();
    this.queryOutWaterOptions();
    this.queryOutRightControl();
  }

  queryOutWaterOptions = () => {
    const {dispatch} = this.props;

    let params = {dataDictTypeCode: 'out_water_control', status: 0};
    dispatch({
      type: 'auditModel/queryDatadict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let waterOptions = [];
          res.data.dataList.forEach(item => {
            waterOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })
          this.setWaterOptions(waterOptions);

        }
      },
    });
  };
  setWaterOptions = (options) => {
    this.setState({waterOptions: options});
  }
  /**
   * 查询外发的权限
   */
  queryOutRightControl = () => {
    const {dispatch} = this.props;
    let params = {dataDictTypeCode: 'out_right_control', status: 0};
    dispatch({
      type: 'auditModel/queryDatadict',
      payload: params,
      callback: (res) => {
        if (res.result == "ok" && res.data) {
          let authOptions = [];
          res.data.dataList.forEach(item => {
            authOptions.push({label: item.dataDictName, value: item.dataDictValue});
          })

          this.setAuthOptions(authOptions);
        }
      },
    });
  };
  setAuthOptions = (options) => {
    this.setState({authOptions: options});
  }



  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const {dispatch} = this.props;
    const {formValues} = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = {...obj};
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});

    const params = {
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }
    this.queryAuditPageList(params, pagination.pageSize, pagination.current - 1)
  };

  previewItem = id => {
    Modal.success({title: `预览文件 id:${id}`});
  };


  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  handleModalVisible = (flag, record) => {
    this.setState({
      modalVisible: !!flag,
    });
    if (flag && record) {
      this.queryApplyDetail(record.id);
    }
  };

  //查询申请详情
  queryApplyDetail = id => {
    const {dispatch} = this.props;
    let queryForm = {id: id};
    dispatch({
      type: 'auditModel/queryApplyDetail',
      payload: queryForm,
    });
  };


  handleSearch = e => {
    e.preventDefault();

    const {dispatch, form} = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
        updatedAt: fieldsValue.updatedAt && fieldsValue.updatedAt.valueOf(),
      };

      this.setState({
        formValues: values,
      });
      this.queryAuditPageList(values)

    });
  };

  renderSimpleForm() {
    const {
      form: {getFieldDecorator},
    } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{md: 8, lg: 24, xl: 48}}>
          <Col md={8} sm={24}>
            <FormItem label="申请来源">
              {getFieldDecorator('applyType')(
                <Select placeholder="请选择" style={{width: '100%'}}>
                  <Option value="">--请选择--</Option>
                  <Option value={2}>流转</Option>
                  <Option value={3}>外发</Option>
                  <Option value={4}>编辑</Option>
                  <Option value={0}>个人文件下载</Option>
                  <Option value={1}>公共文件下载</Option>
                  <Option value={5}>自定义组文件下载</Option>
                </Select>
              )}
            </FormItem>
          </Col>

          <Col md={8} sm={24}>
            <span className={styles.submitButtons}>
              <Button type="primary" htmlType="submit">
                查询
              </Button>
            </span>
          </Col>
        </Row>
      </Form>
    );
  }

  renderForm() {
    return this.renderSimpleForm();
  }

  queryAuditPageList(params, pageSize = 10, pageNum = 0) {
    const {dispatch} = this.props;
    if (!params) {
      params = {};
    }
    params.applyStateList = [];
    params.applyStateList[0] = 1;
    params.applyStateList[1] = 2;
    params["sortInfos[" +0 + "].sort"] = "DESC";
    params["sortInfos[" +0 + "].field"] = "updateTime";
    const values = {
      pageSize: pageSize, //分页每页条数
      pageNum: pageNum, //分页页码
    };
    const assignObj = Object.assign(params, values);
    dispatch({
      type: 'auditModel/queryAuditPageList',
      payload: assignObj,
    });
  }

  render() {
    const {
      auditModel: {data, detail},
      loading,
    } = this.props;
    const {selectedRows, modalVisible,waterOptions,authOptions,} = this.state;
    const parentMethods = {
      handleModalVisible: this.handleModalVisible,
    };
    return (
      <Card bordered={false}>
        <div className={styles.tableList}>
          <div className={styles.tableListForm}>{this.renderForm()}</div>

          <TableList
            className={styles.tdPadding}
            hideRowSelection={true}
            selectedRows={selectedRows}
            loading={loading}
            data={data}
            columns={this.columns}
            onSelectRow={this.handleSelectRows}
            onChange={this.handleStandardTableChange}
          />
        </div>
        <ApplyDetailForm waterOptions={waterOptions} authOptions={authOptions} {...parentMethods} record={detail} modalVisible={modalVisible}/>
      </Card>
    );
  }
}

export default AuditDone;
